<?php

namespace App\Http\Utils\Promotion;


use App\Http\Utils\Integral\Time;
use Illuminate\Support\Facades\DB;

class User
{
    /**
     * 平台积分发放手续费
     * @var float
     */
    private $platform = 0;

    /**
     * 平台积分发放手续费
     * @var float
     */
    private $userform = 1;

    /**
     * 用户ID
     * @var string
     */
    public $userId;

    /**
     * 商户ID
     * @var string
     */
    public $shopId;

    /**
     * User constructor.
     * @param string $userId
     * @param string $shopId
     */
    public function __construct($userId, $shopId)
    {
        $this->userId = $userId;
        $this->shopId = $shopId;
        $this->earnings();
    }

    /**
     * @var int
     */
    private $balance = 0;

    /**
     *
     */
    private function earnings()
    {
        $balance = DB::table('promotion_user')
            ->where([
                'user_id' => $this->userId,
                'shop_id' => $this->shopId,
            ])->lockForUpdate()
            ->value('balance');
        if (is_null($balance)) {
            DB::table('promotion_user')
                ->insert([
                    'user_id'     => $this->userId,
                    'shop_id'     => $this->shopId,
                    'balance'     => 0,
                    'create_time' => Time::current(),
                    'update_time' => Time::current(),
                ]);
            $this->balance = 0;
        } else {
            $this->balance = $balance;
        }
    }

    /**
     * @var array
     */
    private $flows = [];

    /**
     * @param string $orderNum
     * @param string $info
     * @param float $amount
     * @param int $planId
     */
    public function flow($orderNum, $info, $amount, $planId)
    {
        $this->balance = $this->balance + $amount * $this->userform;
        $this->flows[] = [
            'user_id'     => $this->userId,
            'shop_id'     => $this->shopId,
            'order_num'   => $orderNum,
            'info'        => $info,
            'amount'      => $amount * $this->userform,
            'should'      => $amount,
            'platform'    => $amount * $this->platform,
            'history'     => $this->balance,
            'plan_id'     => $planId,
            'read'        => 'false',
            'create_time' => Time::current(),
            'update_time' => Time::current(),
        ];
    }

    /**
     *
     */
    public function userRecord()
    {
        DB::table('promotion_user_flow')->insert($this->flows);
        DB::table('promotion_user')
            ->where([
                'user_id' => $this->userId,
                'shop_id' => $this->shopId,
            ])
            ->update([
                'balance'     => $this->balance,
                'update_time' => Time::current(),
            ]);
    }
}